﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Noria.Web.MyMSDN.Models;

namespace Noria.Web.Utility
{
    /// <summary>
    /// Restore the database to the specific version
    /// </summary>
    public class RestoreHandler : IHttpHandler
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod != "POST")
                throw new MethodNotAllowedException();

            var file = context.Request.QueryString["z"];
            var content = System.IO.File.ReadAllBytes(Path.Combine(
                context.Server.MapPath("tmp/backup"), file));

            var raw = GZipHelper.Decompress(content);
            var rawText = Encoding.UTF8.GetString(raw);
            var cats = JsonConvert.DeserializeObject<Category[]>(rawText);

            using (var db = new MmContext())
            {
                db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=0");
                db.Database.ExecuteSqlCommand("truncate `file`");
                db.Database.ExecuteSqlCommand("truncate `family`");
                db.Database.ExecuteSqlCommand("truncate `category`");
                db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=1");
                log.Info("mymsdn database has been truncated.");

                foreach (var cat in cats)
                {
                    db.Categories.Add(cat);
                }
                int s = db.SaveChanges();
                log.InfoFormat("Data restored. count={0}", s);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}